<!DOCTYPE html>
<html>
<head>
    <title>文件传输工具</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        :root {
            --mac-bg: #f5f5f7;
            --mac-panel: #ffffff;
            --mac-border: #d2d2d7;
            --mac-text: #1d1d1f;
            --mac-secondary: #86868b;
            --mac-accent: #0071e3;
            --mac-accent-hover: #0077ed;
            --mac-danger: #ff3b30;
            --mac-success: #34c759;
            --mac-warning: #ff9500;
            --mac-info: #5856d6;
            --mac-shadow: rgba(0, 0, 0, 0.05);
            --mac-radius: 10px;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background-color: var(--mac-bg);
            color: var(--mac-text);
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
        }
        
        .header {
            background-color: var(--mac-panel);
            border-bottom: 1px solid var(--mac-border);
            padding: 12px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 1px 3px var(--mac-shadow);
            z-index: 10;
            position: relative;
        }
        
        .header h1 {
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            margin: 0;
            font-size: 20px;
            font-weight: 500;
            color: var(--mac-text);
        }
        
        .user-info {
            margin-left: auto;
            display: flex;
            align-items: center;
            gap: 15px;
            font-size: 14px;
        }
        
        .logout-btn {
            color: var(--mac-accent);
            text-decoration: none;
            font-size: 14px;
            padding: 4px 8px;
            border-radius: 6px;
            transition: background-color 0.2s;
        }
        
        .logout-btn:hover {
            background-color: rgba(0, 113, 227, 0.1);
        }
        
        .main-content {
            display: flex;
            flex: 1;
            padding: 20px;
            gap: 20px;
            overflow: hidden;
            height: calc(100vh - 52px); /* 减去header高度 */
        }
        
        .file-panels {
            display: flex;
            flex: 1;
            gap: 20px;
            overflow: hidden;
            height: 100%;
        }
        
        .panel, .status-panel {
            flex: 1;
            background-color: var(--mac-panel);
            border-radius: var(--mac-radius);
            border: 1px solid var(--mac-border);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            box-shadow: 0 2px 10px var(--mac-shadow);
            transition: box-shadow 0.3s;
            min-width: 0; /* 允许面板收缩 */
        }
        
        .status-panel {
            width: auto; /* 移除固定宽度 */
            margin: 0;
        }
        
        .panel:hover {
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
        }
        
        .panel-title {
            margin: 0;
            padding: 16px;
            font-size: 15px;
            font-weight: 500;
            border-bottom: 1px solid var(--mac-border);
            background-color: rgba(0, 0, 0, 0.02);
            display: flex;
            align-items: center;
        }
        
        .panel-title::before {
            content: "";
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
            background-color: var(--mac-accent);
        }
        
        .file-list {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }
        
        .file-item {
            display: flex;
            align-items: center;
            padding: 8px 12px;
            border-radius: 6px;
            margin-bottom: 4px;
            transition: background-color 0.2s;
        }
        
        .file-item.folder {
            cursor: pointer;
        }
        
        .file-item.folder:hover {
            background-color: rgba(0, 0, 0, 0.05);
        }
        
        .file-item input[type="checkbox"] {
            margin-right: 8px;
            width: 16px;
            height: 16px;
            accent-color: var(--mac-accent);
            cursor: pointer;
        }
        
        .file-icon {
            margin-right: 8px;
            font-size: 16px;
            width: 20px;
            text-align: center;
        }
        
        .file-name {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .file-size {
            color: var(--mac-secondary);
            margin: 0 12px;
            font-size: 12px;
            min-width: 60px;
            text-align: right;
        }
        
        .file-date {
            color: var(--mac-secondary);
            font-size: 12px;
            min-width: 150px;
            text-align: right;
        }
        
        .status-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 16px;
            background-color: rgba(0, 0, 0, 0.02);
            border-bottom: 1px solid var(--mac-border);
        }
        
        .status-title {
            font-size: 14px;
            font-weight: 500;
            margin: 0;
            display: flex;
            align-items: center;
        }
        
        .status-title::before {
            content: "";
            display: inline-block;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            margin-right: 8px;
            background-color: var(--mac-info);
        }
        
        .status-controls {
            display: flex;
            gap: 10px;
        }
        
        .status-content {
            flex: 1;
            overflow-y: auto;
            padding: 12px;
            font-family: "SF Mono", Monaco, Consolas, monospace;
            font-size: 12px;
            line-height: 1.5;
        }
        
        .status-item {
            padding: 12px;
            margin-bottom: 10px;
            border-radius: 8px;
            border-left: 3px solid transparent;
            box-shadow: 0 1px 3px var(--mac-shadow);
            transition: transform 0.2s;
        }
        
        .status-item:hover {
            transform: translateY(-2px);
        }
        
        .status-pending {
            background-color: rgba(255, 149, 0, 0.1);
            border-left-color: var(--mac-warning);
        }
        
        .status-transferring {
            background-color: rgba(88, 86, 214, 0.1);
            border-left-color: var(--mac-info);
        }
        
        .status-success {
            background-color: rgba(52, 199, 89, 0.1);
            border-left-color: var(--mac-success);
        }
        
        .status-error {
            background-color: rgba(255, 59, 48, 0.1);
            border-left-color: var(--mac-danger);
        }
        
        .status-header .filename {
            font-weight: 500;
        }
        
        .status-header .timestamp {
            color: var(--mac-secondary);
            font-size: 12px;
        }
        
        .status-content {
            color: var(--mac-secondary);
        }
        
        .log-entry {
            padding: 6px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            display: flex;
            align-items: baseline;
        }
        
        .log-time {
            color: var(--mac-secondary);
            margin-right: 10px;
            font-size: 11px;
            min-width: 70px;
        }
        
        .log-info {
            color: var(--mac-info);
        }
        
        .log-warning {
            color: var(--mac-warning);
        }
        
        .log-error {
            color: var(--mac-danger);
        }
        
        .log-success {
            color: var(--mac-success);
        }
        
        button {
            padding: 6px 12px;
            background-color: var(--mac-accent);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        
        button:hover {
            background-color: var(--mac-accent-hover);
            transform: translateY(-1px);
        }
        
        button:active {
            transform: translateY(0);
        }
        
        button:disabled {
            background-color: var(--mac-secondary);
            cursor: not-allowed;
            transform: none;
        }
        
        .debug-btn {
            background-color: transparent;
            color: var(--mac-text);
            border: 1px solid var(--mac-border);
        }
        
        .debug-btn:hover {
            background-color: rgba(0, 0, 0, 0.05);
        }
        
        .debug-btn.active {
            background-color: var(--mac-accent);
            color: white;
            border-color: var(--mac-accent);
        }
        
        .empty-message {
            color: var(--mac-secondary);
            font-style: italic;
            padding: 20px;
            text-align: center;
        }
        
        /* 滚动条样式 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: transparent;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        
        /* 确认对话框样式 */
        .confirm-dialog {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            backdrop-filter: blur(5px);
        }
        
        .confirm-content {
            background-color: var(--mac-panel);
            padding: 24px;
            border-radius: var(--mac-radius);
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
            max-width: 400px;
            width: 90%;
            animation: fadeIn 0.3s;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .confirm-content p {
            margin: 0 0 20px 0;
            white-space: pre-line;
            font-size: 14px;
            line-height: 1.5;
        }
        
        .confirm-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        
        .confirm-buttons button {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
        }
        
        .confirm-buttons button:first-child {
            background-color: var(--mac-danger);
            color: white;
        }
        
        .confirm-buttons button:last-child {
            background-color: var(--mac-secondary);
            color: white;
        }
        
        /* 按钮容器 */
        .button-container {
            padding: 12px;
            text-align: right;
            border-top: 1px solid var(--mac-border);
            background-color: rgba(0, 0, 0, 0.02);
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .file-panels {
                flex-direction: column;
            }
            
            .panel {
                margin-bottom: 20px;
            }
            
            .status-panel {
                margin: 0 0 20px 0;
            }
        }
        
        .refresh-btn {
            margin-right: 8px;
            background-color: var(--mac-secondary);
        }
        
        .refresh-btn:hover {
            background-color: var(--mac-accent);
        }
        
        /* 面包屑导航 */
        .breadcrumb {
            padding: 8px 12px;
            background-color: rgba(0, 0, 0, 0.02);
            border-bottom: 1px solid var(--mac-border);
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .breadcrumb-item {
            color: var(--mac-accent);
            cursor: pointer;
        }
        
        .breadcrumb-item:hover {
            text-decoration: underline;
        }
        
        .breadcrumb-separator {
            color: var(--mac-secondary);
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>文件传输工具</h1>
        <div class="user-info">
            <span>欢迎，{{ current_user.username }}</span>
            <a href="{{ url_for('auth.logout') }}" class="logout-btn">登出</a>
        </div>
    </div>
    
    <div class="main-content">
        <div class="file-panels">
            <!-- 源文件列表面板 -->
            <div class="panel">
                <h2 class="panel-title">源服务器文件列表</h2>
                <div class="file-list" id="sourceFiles">
                    {% if source_files %}
                        {% for file in source_files %}
                            <div class="file-item {% if file.type == 'directory' %}folder{% endif %}" 
                                 data-path="{{ file.name }}"
                                 data-type="{{ file.type }}">
                                <input type="checkbox" id="source_file_${loop.index}" value="{{ file.name }}" 
                                       {% if file.type == 'directory' %}disabled{% endif %}>
                                <span class="file-icon">{{ "📁" if file.type == 'directory' else "📄" }}</span>
                                <span class="file-name">{{ file.name }}</span>
                                {% if file.type == 'file' %}
                                    <span class="file-size">{{ file.size }}</span>
                                    <span class="file-date">{{ file.mtime }}</span>
                                {% endif %}
                            </div>
                        {% endfor %}
                    {% else %}
                        <div class="file-item empty-message">目录为空</div>
                    {% endif %}
                </div>
                <div class="button-container">
                    <button onclick="refreshSourceFiles()" class="refresh-btn">刷新列表</button>
                    <button onclick="startTransfer()" id="transferBtn">开始传输</button>
                </div>
            </div>

            <!-- 传输状态面板 -->
            <div class="status-panel">
                <div class="status-header">
                    <h3 class="status-title">传输状态</h3>
                    <div class="status-controls">
                        <button id="debugBtn" class="debug-btn" onclick="toggleDebug()">调试模式</button>
                    </div>
                </div>
                <div class="status-content" id="transferStatus">
                    <!-- 传输状态将在这里显示 -->
                </div>
            </div>

            <!-- 目标文件列表面板 -->
            <div class="panel">
                <h2 class="panel-title">目标服务器文件列表</h2>
                <div class="file-list" id="destinationFiles">
                    {% if destination_files %}
                        {% for file in destination_files %}
                            <div class="file-item {% if file.type == 'directory' %}folder{% endif %}" 
                                 data-path="{{ file.path }}"
                                 data-type="{{ file.type }}">
                                <span class="file-icon">{{ "📁" if file.type == 'directory' else "📄" }}</span>
                                <span class="file-name">{{ file.name }}</span>
                                {% if file.type == 'file' %}
                                    <span class="file-size">{{ file.size }}</span>
                                    <span class="file-date">{{ file.mtime }}</span>
                                {% endif %}
                            </div>
                        {% endfor %}
                    {% else %}
                        <div class="file-item empty-message">目录为空</div>
                    {% endif %}
                </div>
                <div class="button-container">
                    <button onclick="refreshDestinationFiles()">刷新列表</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 调试模式状态
        let debugMode = false;
        let logEntries = [];
        
        // 切换调试模式
        function toggleDebug() {
            debugMode = !debugMode;
            const debugBtn = document.getElementById('debugBtn');
            const statusTitle = document.querySelector('.status-title');
            debugBtn.classList.toggle('active', debugMode);
            
            // 更新状态面板标题
            statusTitle.textContent = debugMode ? '日志打印' : '传输状态';
            
            // 更新状态面板显示
            updateStatusDisplay();
        }
        
        // 更新状态面板显示
        function updateStatusDisplay() {
            const statusDiv = document.getElementById('transferStatus');
            
            if (debugMode) {
                // 显示所有日志
                statusDiv.innerHTML = logEntries.map(entry => `
                    <div class="log-entry">
                        <span class="log-time">${entry.time}</span>
                        <span class="log-${entry.type}">${entry.message}</span>
                    </div>
                `).join('');
            } else {
                // 只显示传输状态
                const transferStatuses = document.querySelectorAll('.status-item');
                statusDiv.innerHTML = '';
                transferStatuses.forEach(status => {
                    statusDiv.appendChild(status.cloneNode(true));
                });
            }
        }
        
        // 添加日志条目
        function addLogEntry(type, message) {
            const time = new Date().toLocaleTimeString();
            logEntries.push({ time, type, message });
            
            // 如果日志太多，删除旧的
            if (logEntries.length > 100) {
                logEntries.shift();
            }
            
            // 如果调试模式开启，更新显示
            if (debugMode) {
                updateStatusDisplay();
            }
        }
        
        // 生成唯一ID的函数
        function generateTransferId() {
            return 'transfer_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        // 检查文件是否存在
        async function checkFileExists(filename) {
            try {
                addLogEntry('info', `检查文件是否存在: ${filename}`);
                const response = await fetch('/check-file-exists', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'filename=' + encodeURIComponent(filename)
                });
                const data = await response.json();
                addLogEntry('info', `文件 ${filename} ${data.exists ? '已存在' : '不存在'}`);
                return data.exists;
            } catch (error) {
                addLogEntry('error', `检查文件存在性失败: ${error}`);
                console.error('检查文件存在性失败:', error);
                return false;
            }
        }

        // 创建确认对话框
        function createConfirmDialog(message) {
            return new Promise((resolve) => {
                const dialog = document.createElement('div');
                dialog.className = 'confirm-dialog';
                dialog.innerHTML = `
                    <div class="confirm-content">
                        <p>${message}</p>
                        <div class="confirm-buttons">
                            <button onclick="this.closest('.confirm-dialog').dispatchEvent(new CustomEvent('confirm', {detail: true}))">确认</button>
                            <button onclick="this.closest('.confirm-dialog').dispatchEvent(new CustomEvent('confirm', {detail: false}))">取消</button>
                        </div>
                    </div>
                `;
                
                document.body.appendChild(dialog);
                
                const handleConfirm = (event) => {
                    dialog.remove();
                    resolve(event.detail);
                };
                
                dialog.addEventListener('confirm', handleConfirm);
            });
        }

        // 添加文件路径处理函数
        function getRelativePath(fullPath, basePath) {
            return fullPath.substring(basePath.length).replace(/^[\/\\]/, '');
        }

        // 修改文件列表显示函数
        function displayFiles(files, container, basePath) {
            container.innerHTML = '';
            if (files.length === 0) {
                container.innerHTML = '<div class="empty-message">目录为空</div>';
                return;
            }

            files.forEach((file, index) => {
                const relativePath = getRelativePath(file.path, basePath);
                const fileItem = document.createElement('div');
                fileItem.className = `file-item ${file.type === 'directory' ? 'folder' : ''}`;
                fileItem.dataset.path = relativePath;
                fileItem.dataset.type = file.type;

                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.id = `file_${index}`;
                checkbox.value = relativePath;
                if (file.type === 'directory') {
                    checkbox.disabled = true;
                }

                const fileIcon = document.createElement('span');
                fileIcon.className = 'file-icon';
                fileIcon.textContent = file.type === 'directory' ? '📁' : '📄';

                const fileInfo = document.createElement('div');
                fileInfo.className = 'file-info';

                const fileName = document.createElement('span');
                fileName.className = 'file-name';
                fileName.textContent = relativePath;

                const fileMeta = document.createElement('div');
                fileMeta.className = 'file-meta';

                if (file.type === 'file') {
                    const fileSize = document.createElement('span');
                    fileSize.className = 'file-size';
                    fileSize.textContent = file.size || '';

                    const fileDate = document.createElement('span');
                    fileDate.className = 'file-date';
                    fileDate.textContent = file.mtime || '';

                    fileMeta.appendChild(fileSize);
                    fileMeta.appendChild(fileDate);
                }

                fileInfo.appendChild(fileName);
                fileInfo.appendChild(fileMeta);

                fileItem.appendChild(checkbox);
                fileItem.appendChild(fileIcon);
                fileItem.appendChild(fileInfo);
                container.appendChild(fileItem);
            });
        }

        // 修改传输函数
        async function startTransfer() {
            const sourceFiles = Array.from(document.querySelectorAll('#sourceFiles input[type="checkbox"]:checked'))
                .map(cb => {
                    // 获取完整的相对路径
                    const fileItem = cb.closest('.file-item');
                    const path = fileItem.dataset.path;
                    // 如果当前在子目录中，将当前路径和文件名组合
                    const fullPath = currentPath ? `${currentPath}/${path}` : path;
                    return fullPath;
                });
            
            if (sourceFiles.length === 0) {
                alert('请选择要传输的文件');
                return;
            }
            
            const confirmed = await createConfirmDialog(`确定要传输选中的 ${sourceFiles.length} 个文件吗？`);
            
            if (!confirmed) return;
            
            // 清空状态面板
            document.getElementById('transferStatus').innerHTML = '';
            
            // 为每个文件创建状态项
            sourceFiles.forEach(filename => {
                const statusItem = document.createElement('div');
                statusItem.className = 'status-item';
                statusItem.innerHTML = `
                    <span class="filename">${filename}</span>
                    <span class="status">准备传输...</span>
                `;
                document.getElementById('transferStatus').appendChild(statusItem);
            });
            
            // 开始传输
            for (const filename of sourceFiles) {
                try {
                    addLogEntry('info', `开始传输文件: ${filename}`);
                    const response = await fetch('/transfer', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: `filename=${encodeURIComponent(filename)}`
                    });
                    
                    const result = await response.json();
                    // 使用更可靠的选择器方式
                    const statusItems = document.querySelectorAll('.status-item');
                    const statusItem = Array.from(statusItems).find(item => 
                        item.querySelector('.filename').textContent === filename
                    );
                    
                    if (statusItem) {
                        if (result.success) {
                            statusItem.querySelector('.status').textContent = '传输成功';
                            statusItem.classList.add('status-success');
                            addLogEntry('success', `文件 ${filename} 传输成功`);
                        } else {
                            statusItem.querySelector('.status').textContent = `传输失败: ${result.message}`;
                            statusItem.classList.add('status-error');
                            addLogEntry('error', `文件 ${filename} 传输失败: ${result.message}`);
                        }
                    }
                } catch (error) {
                    console.error('传输失败:', error);
                    const statusItems = document.querySelectorAll('.status-item');
                    const statusItem = Array.from(statusItems).find(item => 
                        item.querySelector('.filename').textContent === filename
                    );
                    
                    if (statusItem) {
                        statusItem.querySelector('.status').textContent = `传输失败: ${error.message}`;
                        statusItem.classList.add('status-error');
                        addLogEntry('error', `文件 ${filename} 传输失败: ${error.message}`);
                    }
                }
            }
            
            // 刷新目标文件列表
            refreshDestinationFiles();
        }

        // 页面加载时初始化文件列表
        document.addEventListener('DOMContentLoaded', () => {
            const sourcePath = '{{ config["SOURCE_PATH"] }}';
            const destPath = '{{ config["DESTINATION_PATH"] }}';
            
            // 获取并显示源文件列表
            fetch('/source-files')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayFiles(data.files, document.getElementById('sourceFiles'), sourcePath);
                    } else {
                        console.error('获取源文件列表失败:', data.message);
                    }
                });
            
            // 获取并显示目标文件列表
            fetch('/destination-files')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayFiles(data.files, document.getElementById('destinationFiles'), destPath);
                    } else {
                        console.error('获取目标文件列表失败:', data.message);
                    }
                });
        });

        function refreshDestinationFiles() {
            addLogEntry('info', '刷新目标文件列表');
            const path = currentDestPath || '';
            fetch(`/destination-files?path=${encodeURIComponent(path)}`)
                .then(response => response.json())
                .then(data => {
                    const destinationDiv = document.getElementById('destinationFiles');
                    if (data.files && data.files.length > 0) {
                        destinationDiv.innerHTML = data.files.map((file, index) => `
                            <div class="file-item ${file.type === 'directory' ? 'folder' : ''}" 
                                 data-path="${file.path || file.name}"
                                 data-type="${file.type}">
                                <span class="file-icon">${file.type === 'directory' ? '📁' : '📄'}</span>
                                <span class="file-name">${file.name}</span>
                                ${file.type === 'file' ? `
                                    <span class="file-size">${file.size}</span>
                                    <span class="file-date">${new Date(file.mtime * 1000).toLocaleString()}</span>
                                ` : ''}
                            </div>
                        `).join('');
                        
                        // 添加目标文件夹点击事件
                        document.querySelectorAll('#destinationFiles .file-item.folder').forEach(item => {
                            item.addEventListener('click', (e) => {
                                // 防止事件冒泡
                                e.stopPropagation();
                                const path = item.dataset.path;
                                navigateToDestFolder(path);
                            });
                        });
                        
                        addLogEntry('success', `目标文件列表已更新，共 ${data.files.length} 个文件/文件夹`);
                    } else {
                        destinationDiv.innerHTML = '<div class="file-item empty-message">目录为空</div>';
                        addLogEntry('info', '目标目录为空');
                    }
                })
                .catch(error => {
                    addLogEntry('error', `刷新目标文件列表失败: ${error}`);
                    alert('刷新目标文件列表失败：' + error);
                });
        }
        
        // 初始化日志
        addLogEntry('info', '应用已启动');

        let currentPath = '';

        // 刷新源文件列表
        async function refreshSourceFiles() {
            try {
                addLogEntry('info', '刷新源文件列表');
                const response = await fetch(`/refresh-source-files?path=${encodeURIComponent(currentPath)}`);
                const data = await response.json();
                
                const sourceFilesDiv = document.getElementById('sourceFiles');
                if (data.files && data.files.length > 0) {
                    sourceFilesDiv.innerHTML = data.files.map((file, index) => `
                        <div class="file-item ${file.type === 'directory' ? 'folder' : ''}" 
                             data-path="${file.name}"
                             data-type="${file.type}">
                            <input type="checkbox" id="source_file_${index}" value="${file.name}" 
                                   ${file.type === 'directory' ? 'disabled' : ''}>
                            <span class="file-icon">${file.type === 'directory' ? '📁' : '📄'}</span>
                            <span class="file-name">${file.name}</span>
                            ${file.type === 'file' ? `
                                <span class="file-size">${file.size}</span>
                                <span class="file-date">${file.mtime}</span>
                            ` : ''}
                        </div>
                    `).join('');
                    
                    // 添加源文件夹点击事件
                    document.querySelectorAll('#sourceFiles .file-item.folder').forEach(item => {
                        item.addEventListener('click', (e) => {
                            if (e.target.tagName !== 'INPUT') {
                                const path = item.dataset.path;
                                navigateToFolder(path);
                            }
                        });
                    });
                    
                    addLogEntry('success', `源文件列表已更新，共 ${data.files.length} 个文件/文件夹`);
                } else {
                    sourceFilesDiv.innerHTML = '<div class="file-item empty-message">目录为空</div>';
                    addLogEntry('info', '源目录为空');
                }
            } catch (error) {
                addLogEntry('error', `刷新源文件列表失败: ${error}`);
                alert('刷新源文件列表失败：' + error);
            }
        }

        // 导航到源文件夹
        async function navigateToFolder(folderName) {
            try {
                currentPath = currentPath ? `${currentPath}/${folderName}` : folderName;
                addLogEntry('info', `进入源文件夹: ${currentPath}`);
                
                // 更新源文件面包屑导航
                updateBreadcrumb();
                
                // 刷新源文件列表
                await refreshSourceFiles();
            } catch (error) {
                addLogEntry('error', `进入源文件夹失败: ${error}`);
                alert('进入源文件夹失败：' + error);
            }
        }

        // 更新源文件面包屑导航
        function updateBreadcrumb() {
            const breadcrumbDiv = document.createElement('div');
            breadcrumbDiv.className = 'breadcrumb';
            
            // 添加根目录
            breadcrumbDiv.innerHTML = `
                <span class="breadcrumb-item" onclick="navigateToRoot()">根目录</span>
            `;
            
            // 添加当前路径
            if (currentPath) {
                const paths = currentPath.split('/');
                let currentPathBuilder = '';
                
                paths.forEach((path, index) => {
                    currentPathBuilder += (index === 0 ? '' : '/') + path;
                    breadcrumbDiv.innerHTML += `
                        <span class="breadcrumb-separator">/</span>
                        <span class="breadcrumb-item" onclick="navigateToPath('${currentPathBuilder}')">${path}</span>
                    `;
                });
            }
            
            // 替换现有的面包屑导航
            const existingBreadcrumb = document.querySelector('.breadcrumb');
            if (existingBreadcrumb) {
                existingBreadcrumb.replaceWith(breadcrumbDiv);
            } else {
                document.querySelector('.panel-title').after(breadcrumbDiv);
            }
        }

        // 导航到根目录
        function navigateToRoot() {
            currentPath = '';
            updateBreadcrumb();
            refreshSourceFiles();
        }

        // 导航到指定路径
        function navigateToPath(path) {
            currentPath = path;
            updateBreadcrumb();
            refreshSourceFiles();
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            // 初始化源文件列表
            refreshSourceFiles();
            
            // 初始化目标文件列表
            refreshDestinationFiles();
        });

        let currentDestPath = '';

        // 导航到目标文件夹
        async function navigateToDestFolder(folderName) {
            try {
                // 防止路径重复
                if (currentDestPath && currentDestPath.endsWith(folderName)) {
                    return;
                }
                
                currentDestPath = currentDestPath ? `${currentDestPath}/${folderName}` : folderName;
                addLogEntry('info', `进入目标文件夹: ${currentDestPath}`);
                
                // 更新目标文件面包屑导航
                updateDestBreadcrumb();
                
                // 刷新目标文件列表
                await refreshDestinationFiles();
            } catch (error) {
                addLogEntry('error', `进入目标文件夹失败: ${error}`);
                alert('进入目标文件夹失败：' + error);
            }
        }

        // 更新目标文件面包屑导航
        function updateDestBreadcrumb() {
            const breadcrumbDiv = document.createElement('div');
            breadcrumbDiv.className = 'breadcrumb';
            
            // 添加根目录
            breadcrumbDiv.innerHTML = `
                <span class="breadcrumb-item" onclick="navigateToDestRoot()">根目录</span>
            `;
            
            // 添加当前路径
            if (currentDestPath) {
                const paths = currentDestPath.split('/');
                let currentPathBuilder = '';
                
                paths.forEach((path, index) => {
                    currentPathBuilder += (index === 0 ? '' : '/') + path;
                    breadcrumbDiv.innerHTML += `
                        <span class="breadcrumb-separator">/</span>
                        <span class="breadcrumb-item" onclick="navigateToDestPath('${currentPathBuilder}')">${path}</span>
                    `;
                });
            }
            
            // 替换现有的面包屑导航
            const existingBreadcrumb = document.querySelector('.panel:last-child .breadcrumb');
            if (existingBreadcrumb) {
                existingBreadcrumb.replaceWith(breadcrumbDiv);
            } else {
                document.querySelector('.panel:last-child .panel-title').after(breadcrumbDiv);
            }
        }

        // 导航到目标根目录
        function navigateToDestRoot() {
            currentDestPath = '';
            updateDestBreadcrumb();
            refreshDestinationFiles();
        }

        // 导航到指定目标路径
        function navigateToDestPath(path) {
            currentDestPath = path;
            updateDestBreadcrumb();
            refreshDestinationFiles();
        }
    </script>
</body>
</html>
